﻿//2.两数相加
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* temp = head;

    int carry = 0;
    while (l1 != NULL || l2 != NULL)
    {
        struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        if (l1 == NULL)
        {
            newnode->val = (l2->val + carry) % 10;
            carry = (l2->val + carry) / 10;
            l2 = l2->next;
        }
        else if (l2 == NULL)
        {
            newnode->val = (l1->val + carry) % 10;
            carry = (l1->val + carry) / 10;
            l1 = l1->next;
        }
        else
        {
            newnode->val = (l1->val + l2->val + carry) % 10;
            carry = (l1->val + l2->val + carry) / 10;
            l1 = l1->next;
            l2 = l2->next;
        }

        temp->next = newnode;
        temp = temp->next;
    }
    if (carry != 0)
    {
        struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newnode->next = NULL;
        newnode->val = carry;
        temp->next = newnode;
    }

    return head->next;
}

